import { ref, reactive } from 'vue'
import formDrawer from '@/components/FormDrawer.vue'
import { updatepassword } from "@/api/manager"
import { showModel,toast } from "@/utils/toast"
import { useRouter } from "vue-router"
// import { useStore } from "vuex"
import { useFullscreen } from '@vueuse/core'
import { useUserStore } from '@/stores/user'

export function useRepassword() {
    const router = useRouter()
    // const store = useStore()
    const store = useUserStore()
    // 修改密码
    const formDrawerRef = ref(null)
    const form = reactive({
        oldpassword: "",
        password: "",
        repassword: ""
    })
    let repeatValidate = (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }}
    
    const rules = {
        oldpassword: [
            {
                required: true,
                message: '旧密码不能为空',
                trigger: 'blur'
            },
        ],
        password: [
            {
                required: true,
                message: '新密码不能为空',
                trigger: 'blur'
            },
        ],
        repassword: [
            {
                required: true,
                message: '确认密码不能为空',
                trigger: 'blur'
            },
            { validator: repeatValidate, trigger: 'blur' } // 2密码不一致
        ]
    }

    const formRef = ref(null)
    const onSubmit = () => {
        formRef.value.validate((valid) => {
            if (!valid) {
                return false
            }
            formDrawerRef.value.showLoading()
            updatepassword(form)
                .then(res => {
                    // toast("修改密码成功，请重新登录")
                    // store.dispatch("logout")
                    // 跳转回登录页
                    router.push("/login")
                })
                .finally(() => {
                    formDrawerRef.value.hideLoading()
                })

        })
    }

    const openRePasswordForm = () => formDrawerRef.value.open()

    return {
        formDrawerRef,
        form,
        rules,
        formRef,
        onSubmit,
        openRePasswordForm
    }
    
}
export function useLogout() {
    const router = useRouter()
    const store = useUserStore()
    function handleLogout() {
        showModel("是否要退出登陆？")
        .then(() => {
        store.removeToken()
        router.push("/login")
        toast("退出成功")
    })
    }

    return {
        handleLogout
    }
}